// 复用逻辑的函数（钩子）
// 懒加载
// target dom对象 apiFn
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import day from 'dayjs'
export const uselazyData = (target, apiFn) => {
  const results = ref([])
  // stop 停止 监听
  const { stop } = useIntersectionObserver(
    // 监听对象
    target,
    ([{ isIntersecting }], observerElement) => {
      // isIntersecting是否进入可视区
      if (isIntersecting) {
        stop()
        apiFn().then((data) => {
          results.value = data.result
        })
      }
    }
  )
  return { results }
}

// 倒计时
// 需要倒计时的时间
export const usePayTime = () => {
  // 倒计时逻辑
  const time = ref(0)
  const timeText = ref('')
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--
      timeText.value = day.unix(time.value).format('mm分ss秒')
      if (time.value <= 0) {
        pause()
      }
    },
    1000,
    false
  )
  onUnmounted(() => {
    resume()
  })
  // 开启定时器
  const start = (countdown) => {
    time.value = countdown
    timeText.value = day.unix(time.value).format('mm分ss秒')
    resume()
  }
  return {
    start,
    timeText
  }
}
